<?php

namespace iBrand\Shop\Backend\Model;

use Illuminate\Database\Eloquent\Model;

/**
 * 内置模块，不涉及业务逻辑
 */
class Common extends Model
{

    /**
     * 获取中文首字母
     *
     * @param type $str
     *
     * @return boolean|string
     */
    public static function getFirstLetter($str)
    {
        $str = iconv("UTF-8", "gb2312", $str); //如果程序是gbk的，此行就要注释掉
        if (preg_match("/^[\x7f-\xff]/", $str)) {
            $fchar = ord($str{0});
            if ($fchar >= ord("A") and $fchar <= ord("z")) {
                return strtoupper($str{0});
            }
            $a = $str;
            $val = ord($a{0}) * 256 + ord($a{1}) - 65536;
            if ($val >= -20319 and $val <= -20284) {
                return "A";
            }
            if ($val >= -20283 and $val <= -19776) {
                return "B";
            }
            if ($val >= -19775 and $val <= -19219) {
                return "C";
            }
            if ($val >= -19218 and $val <= -18711) {
                return "D";
            }
            if ($val >= -18710 and $val <= -18527) {
                return "E";
            }
            if ($val >= -18526 and $val <= -18240) {
                return "F";
            }
            if ($val >= -18239 and $val <= -17923) {
                return "G";
            }
            if ($val >= -17922 and $val <= -17418) {
                return "H";
            }
            if ($val >= -17417 and $val <= -16475) {
                return "J";
            }
            if ($val >= -16474 and $val <= -16213) {
                return "K";
            }
            if ($val >= -16212 and $val <= -15641) {
                return "L";
            }
            if ($val >= -15640 and $val <= -15166) {
                return "M";
            }
            if ($val >= -15165 and $val <= -14923) {
                return "N";
            }
            if ($val >= -14922 and $val <= -14915) {
                return "O";
            }
            if ($val >= -14914 and $val <= -14631) {
                return "P";
            }
            if ($val >= -14630 and $val <= -14150) {
                return "Q";
            }
            if ($val >= -14149 and $val <= -14091) {
                return "R";
            }
            if ($val >= -14090 and $val <= -13319) {
                return "S";
            }
            if ($val >= -13318 and $val <= -12839) {
                return "T";
            }
            if ($val >= -12838 and $val <= -12557) {
                return "W";
            }
            if ($val >= -12556 and $val <= -11848) {
                return "X";
            }
            if ($val >= -11847 and $val <= -11056) {
                return "Y";
            }
            if ($val >= -11055 and $val <= -10247) {
                return "Z";
            }
        } else {
            return false;
        }
    }

    /**
     * 判断是否为移动端
     *
     * @staticvar type $is_mobile
     * @return boolean
     */
    public static function _is_mobile()
    {
        static $is_mobile;
        if (isset($is_mobile)) {
            return $is_mobile;
        }
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            $is_mobile = false;
        } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
            || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
        ) {
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') === false) {
                $is_mobile = true;
            }
        } else {
            $is_mobile = false;
        }

        return $is_mobile;
    }

    /**
     * 获取用户IP转换城市
     *
     * @return type
     */
    public static function getUserIP()
    {
        $data = (object)['name' => '上海市'];
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = false;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match("/^(10|172\.16|192\.168)\./", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        $ip = $ip ? $ip : $_SERVER['REMOTE_ADDR'];

        if ($ip == '127.0.0.1' OR strstr($ip, "192.168")) {
            return $data;
        }

        $result = self::_curl("http://api.map.baidu.com/location/ip?ak=D160a664f0ecd042b5e225a1332ff805&ip=" . $ip);
        $data->name = $result->content->address;

        return $data;
    }

    /**
     * 地址转QQ地图经纬度
     * 参考：http://lbs.qq.com/webservice_v1/guide-geocoder.html
     *
     * @param type $address
     *
     * @return type
     */
    public static function _store_qq_geocoder($address)
    {
        $settings = settings('storeSystemConfig');
        $key = isset($settings['qqmap_key']) ? $settings['qqmap_key'] : '5DZBZ-EN6AU-6NFVH-4SR2M-WEBF2-D3BPP';

        return self::_curl('http://apis.map.qq.com/ws/geocoder/v1/?address=' . $address . '&key=' . $key);
    }

    /**
     * GPS距离计算
     *
     * @param type $lat1
     * @param type $lng1
     * @param type $lat2
     * @param type $lng2
     *
     * @return type
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000;

        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance / 1000, 1);
    }

    /**
     * CURL简化功能 GET
     *
     * @param type $url
     *
     * @return type
     */
    private static function _curl($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($curl);
        curl_close($curl);

        return json_decode($result);
    }

}
